<?php
declare (strict_types = 1);

namespace app\api\business;

use app\lib\Str;
use app\lib\Time;
use think\Exception;
use think\facade\Log;

class User extends Base {

    protected $userModel;

    public function __construct() {
        $this->userModel = new \app\model\mysql\User();
    }

    public function login($data) : bool {
        if (empty($data["tel"]) || empty($data["code"]) || empty($data["type"])) {
            return false;
        }

        if (cache(config("redis.code_pre").$data["tel"]) != $data["code"]) {
            $this->error = "验证码不正确";
            return false;
        }

        /**
         * 应该在这里做一个防频繁登录
         *  把tel 存入到 redis,以及增加次数，
         *  如果登录次数超过几次，就直接返回false，并告诉登录次数超频，多久之后才能登录
         */
        $loginNum = cache(config("redis.login_num_key") . $data["tel"]);
        if (!empty($loginNum) && intval($loginNum) >= config("redis.login_limit")) {
            $this->error = "登录次数太频繁";
            return false;
        }

        try{
            $model = $this->userModel->getInfoByTel($data['tel']);
            if (!$model){
                $userData = [
                    "username" => "t".$data["tel"],
                    "tel" => $data["tel"],
                    "password" => md5("123456"),
                ];
                $this->userModel->save($userData);
                $model = $this->userModel;
            }

            $info = $model->toArray();
            $token = Str::generateToken($data["tel"]);
            $info["token"] = $token;
            $model->save([
                "last_login_time" => date("Y-m-d H:i:s", time()),
                "last_login_ip" => $data["ip"]
            ]);
            $this->setUserInfo($info);
            cache(config("redis.token_pre") . $token,
                $info, Time::getLoginExpireTime($data["type"]));
            cache(config("redis.login_num_key") . $data["tel"], $loginNum + 1, config("redis.login_num_expire_time"));
        }catch (\Exception $e){
            Log::error($e->getMessage());
            return false;
        }

        return true;
    }

    public static function update(array $data = []) : bool {
        $data = array_filter($data);
        if (!isset($data["token"]) || empty($data["token"])) {
            throw new Exception("请重新登录");
        }
        $token = $data["token"];
        unset($data["token"]);
        $userInfo = cache(config("redis.token_pre") . $token);

        if (!$userInfo ||  !isset($userInfo["id"]) || $userInfo["id"] <= 0) {
            throw new Exception("请重新登录");
        }

        $id = $userInfo["id"];

        if (isset($data["username"]) && $data["username"] != $userInfo["username"] && $userInfo["is_updated_username"] == 0) {
            $data["is_updated_username"] = 1;
        }
        $data["updated_time"] = date("Y-m-d H:i:s", \time());
        $result =  \app\model\mysql\User::updateById($id, $data);

        $userInfo = array_merge($userInfo, $data);

        cache(config("redis.token_pre") . $token, $userInfo);

        return $result;
    }

    public function init($userId = 0) : array {
        //购物车
        $result["cart_num"] = Cart::getCartCount($userId);

        return $result;
    }
}